package zhaomh.zhlib.config;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import zhaomh.zhlib.ModInstance;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Config implements ModInstance {
    private final List<Value> values = new ArrayList<>();
    private final File file;

    /**
     * @param folderName 配置文件所在的文件夹的名称
     * @param fileName 配置文件名，不需要后缀
     */
    public Config(String folderName, String fileName) {
        File folder = new File(mc.runDirectory, folderName);
        folder.mkdirs();
        file = new File(folder, fileName+".json");
    }

    public void addValue(Value value) {
        values.add(value);
    }

    public void addValues(List<Value> values) {
        this.values.addAll(values);
    }

    public void addValues(Value... values) {
        this.values.addAll(List.of(values));
    }

    public List<Value> getValues() {
        return new ArrayList<>(values);
    }

    public Value getValue(String name) {
        for (Value value : values) {
            if (value.getName().equals(name)) {
                return value;
            }
        }

        return null;
    }

    public void save() throws IOException {
        Gson gson = new Gson();
        Map<String,Object> map = new HashMap<>();

        for (Value value : values) {

            if (value instanceof ToggleValue tc) {
                map.put(value.getName(),tc.get());
            } else if (value instanceof EnumValue ec) {
                map.put(value.getName(),ec.get());
            }

        }

        Files.writeString(Paths.get(file.getPath()),gson.toJson(map));
    }

    public void load() throws IOException {
        if (!(file.exists() && file.isFile())) {
            return;
        }
        Gson gson = new Gson();

        Map<String, Object> map = gson.fromJson(Files.readString(Paths.get(file.getPath())), new TypeToken<Map<String, Object>>() {
        }.getType());
        for (Value config : values) {
            Object value = map.get(config.getName());
            if (value == null)
                continue;
            if (config instanceof ToggleValue tc) {
                tc.set(Boolean.parseBoolean(value.toString()));
            } else if (config instanceof EnumValue ec) {
                ec.set(value.toString());
            }

        }
    }
}
